package io.geekidea.boot.warehousentry.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.geekidea.boot.Import.ExcelListener;
import io.geekidea.boot.inventorychange.entity.StoreChange;
import io.geekidea.boot.inventorychange.service.StoreChangeService;
import io.geekidea.boot.outbound.service.OutboundService;
import io.geekidea.boot.salesslip.dto.SalesChartDto;
import io.geekidea.boot.salesslip.service.SalesslipService;
import io.geekidea.boot.warehousentry.dto.StatisticsDto;
import io.geekidea.boot.warehousentry.dto.WarehousentryExcel;
import io.geekidea.boot.warehousentry.uitl.JTime;
import org.apache.commons.lang3.StringUtils;
import io.geekidea.boot.area.entity.Area;
import io.geekidea.boot.area.service.AreaService;
import io.geekidea.boot.auth.util.LoginUtil;
import io.geekidea.boot.common.GroupValidator;
import io.geekidea.boot.common.PageDto;
import io.geekidea.boot.framework.response.ApiResult;
import io.geekidea.boot.materials.entity.Materials;
import io.geekidea.boot.materials.service.MaterialsService;
import io.geekidea.boot.store.entity.Store;
import io.geekidea.boot.store.service.StoreService;
import io.geekidea.boot.supplier.entity.Supplier;
import io.geekidea.boot.supplier.service.SupplierService;
import io.geekidea.boot.warehouse.entity.Warehouse;
import io.geekidea.boot.warehouse.service.WarehouseService;
import io.geekidea.boot.warehousentry.dto.WarehousentryDto;
import io.geekidea.boot.warehousentry.query.entity.Warehousentry;
import io.geekidea.boot.warehousentry.query.WarehousentryQuery;
import io.geekidea.boot.warehousentry.services.WarehousentryService;
import io.geekidea.boot.wltype.entity.WlType;
import io.geekidea.boot.wltype.service.IWlTypeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/warehousentry")
@Tag(name = "入库单管理")
public class WarehousentryController {
    @Resource
    private WarehousentryService warehousentryService;
    @Resource
    private MaterialsService materialsService;
    @Resource
    private SupplierService supplierService;
    @Resource
    private StoreService storeService;
    @Resource
    private IWlTypeService wlTypeService;
    @Resource
    private AreaService areaService;
    @Resource
    private WarehouseService warehouseService;
    @Resource
    private StoreChangeService storeChangeService;
    @Resource
    private OutboundService outboundService;

    @Resource
    private SalesslipService SalesslipService;

    /**
     * 按照多条件组合分页查询战区数据列表
     * @return
     */
    @PostMapping("/searchPage")
    @Operation(summary = "搜索入库单",description = "按照多条件组合分页查询战区数据列表")
    public ApiResult searchPage(@RequestBody WarehousentryQuery warehousentryQuery){
        Page<Warehousentry> page = new Page<>(warehousentryQuery.getPage(), warehousentryQuery.getSize());
        if(StringUtils.isNotBlank(warehousentryQuery.getStartDate())){
            warehousentryQuery.setStartDate(warehousentryQuery.getStartDate()+" 00:00:00");
            warehousentryQuery.setEndDate(warehousentryQuery.getEndDate()+" 23:59:59");
        }
        Page<Warehousentry> pageDto = warehousentryService.warehousentryPage(page, warehousentryQuery);
        PageDto<Warehousentry> pageInfo = new PageDto<>(pageDto.getRecords(),pageDto.getTotal(),pageDto.getSize(),pageDto.getCurrent());
        return ApiResult.success(pageInfo);
    }

    @PostMapping("/getWarehousentry/{id}")
    @Operation(summary = "入库单详情",description = "根据id查询入库单详情")
    public ApiResult getWarehousentry(@PathVariable(value = "id")Integer id){
        final Warehousentry warehousentry = warehousentryService.getById(id);
        Materials materials = new Materials();
        materials.setNumbers(warehousentry.getNumbers());
        List<Materials> list = materialsService.getMaterialsList(materials);
        Map<String,Object> map = new HashMap();
        map.put("warehousentry",warehousentry);
        map.put("list",list);
        return ApiResult.success(map);
    }

    @PostMapping("/remove/{id}")
    @Operation(summary = "删除入库单",description = "逻辑删除")
    public ApiResult removeWarehousentry(@PathVariable(value = "id") Integer id) {
        warehousentryService.removeById(id);
        return ApiResult.success("删除入库单数据成功!");
    }



    @PostMapping("/getNumbers/{storeCode}")
    @Operation(summary = "生成入库单号",description = "根据门店编号生成入库单号")
    public ApiResult getNumbers(@PathVariable String storeCode ){
        Store store = storeService.getById(storeCode);
        String code = generateOrderNumber(store.getCode());
        return ApiResult.success("生成入库单号成功",code);
    }

    @PostMapping("/add")
    @Operation(summary = "添加入库单")
    public ApiResult addWarehousentry(@Validated(value = {GroupValidator.Insert.class})@RequestBody WarehousentryDto warehousentryDto) throws Exception {
        warehousentryDto.setCreatorTime(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
        warehousentryDto.setCreatedTime(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
        warehousentryDto.setCreatorUser(LoginUtil.getUsername());
        warehousentryDto.setCreatedBy(LoginUtil.getUsername());
        Warehousentry warehousentryEntity=new Warehousentry();
        BeanUtil.copyProperties(warehousentryDto,warehousentryEntity);
        boolean flag = warehousentryService.save(warehousentryEntity);
        //判断入库单是否添加成功  添加成功我们物料才加门店物料库
        if (flag){
            //增加物料
            List<Materials> list = new ArrayList<>();
            //解析物料json字符串转json
            String jsonString = warehousentryDto.getJsonStr().replaceAll("\"","'");
            JSONArray jsonArray = new JSONArray(jsonString);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObj = jsonArray.getJSONObject(i);
                //物料名称
                String name = jsonObj.getObj("name").toString();
                if (!name.equals("")&&!name.equals(null)){
                    //物料编码
                    String code = jsonObj.getObj("code").toString();
                    //物料税号
                    String taxsh = jsonObj.getObj("taxsh").toString();
                    //供应商id
                    int supplierId = Integer.parseInt(jsonObj.getObj("supplierId").toString());
                    //库存
                    int totalStock = Integer.parseInt(jsonObj.getObj("totalStock").toString());
                    //创建门店物料库对象  参数赋值
                    Materials bean = new Materials();
                    bean.setCode(code);
                    bean.setName(name);
                    bean.setSupplierId(supplierId);
                    bean.setTotalStock(totalStock);
                    bean.setAvailableInventory(String.valueOf(totalStock));
                    bean.setLockInventory("0");
                    bean.setTaxsh(taxsh);
                    bean.setAreaId(warehousentryEntity.getAreaId());
                    bean.setStoresId(warehousentryEntity.getStoreId());
                    bean.setWarehouseId(warehousentryEntity.getWarehouseId());
                    bean.setNumbers(warehousentryEntity.getNumbers());
                    bean.setCreatedBy(LoginUtil.getUsername());
                    bean.setWarehousingTime(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                    bean.setCreatedTime(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                    list.add(bean);

                    StoreChange storeChange = new StoreChange();
                    storeChange.setWarehouseentrynumber(warehousentryEntity.getNumbers());
                    storeChange.setMaterialcode(jsonObj.getObj("code").toString());
                    storeChange.setMaterialsnmark(jsonObj.getObj("taxsh").toString());
                    storeChange.setNameofmaterial(jsonObj.getObj("name").toString());
//                    storeChange.setMaterialswarehouse(jsonObj.getObj("warehouseName").toString());
                    storeChange.setTypeofchange(warehousentryEntity.getType());
                    storeChange.setChangebehavior("入库新增");
                    storeChange.setQuantityofchange("0");
                    storeChange.setQuantityinstock(String.valueOf(totalStock));
                    storeChange.setAvailablestock(String.valueOf(totalStock));
                    storeChange.setLockininventory("0");
                    storeChange.setTimeofchange(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                    storeChange.setCreatedTime(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                    storeChange.setCreatedBy(LoginUtil.getUsername());
                    storeChange.setAreanameFk(warehousentryEntity.getAreaId());
                    storeChange.setStorenameFk(warehousentryEntity.getStoreId());
                    storeChangeService.save(storeChange);
                }

            }
            //批量插入数据
            materialsService.saveBatch(list);
        }

        return ApiResult.success("添加入库单数据成功！");
    }

    @PostMapping("/update")
    @Operation(summary = "修改入库单")
    public ApiResult updateWarehousentry(@Validated(value = {GroupValidator.Insert.class})@RequestBody WarehousentryDto warehousentryDto) throws Exception {
        warehousentryDto.setUpdatedTime(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
        warehousentryDto.setUpdatedBy(LoginUtil.getUsername());
        Warehousentry warehousentryEntity=new Warehousentry();
        BeanUtil.copyProperties(warehousentryDto,warehousentryEntity);
        boolean flag = warehousentryService.updateById(warehousentryEntity);
        //判断入库单是否添加成功  添加成功我们物料才加门店物料库
        if (flag){
            //先删除原来的物料
            materialsService.delByNumbers(warehousentryEntity.getNumbers());
            //增加物料
            List<Materials> list = new ArrayList<>();
            //解析物料json字符串转json
            String jsonString = warehousentryDto.getJsonStr().replaceAll("\"","'");
            JSONArray jsonArray = new JSONArray(jsonString);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObj = jsonArray.getJSONObject(i);
                //物料名称
                String name = jsonObj.getObj("name").toString();
                if (!name.equals("")&&!name.equals(null)) {
                    //物料编码
                    String code = jsonObj.getObj("code").toString();
                    //物料税号
                    String taxsh = jsonObj.getObj("taxsh").toString();
                    //供应商id
                    int supplierId = Integer.parseInt(jsonObj.getObj("supplierId").toString());
                    //库存
                    int totalStock = Integer.parseInt(jsonObj.getObj("totalStock").toString());
                    //创建门店物料库对象  参数赋值
                    Materials bean = new Materials();
                    bean.setCode(code);
                    bean.setName(name);
                    bean.setSupplierId(supplierId);
                    bean.setTotalStock(totalStock);
                    bean.setAvailableInventory(String.valueOf(totalStock));
                    bean.setLockInventory("0");
                    bean.setTaxsh(taxsh);
                    bean.setAreaId(warehousentryEntity.getAreaId());
                    bean.setStoresId(warehousentryEntity.getStoreId());
                    bean.setWarehouseId(warehousentryEntity.getWarehouseId());
                    bean.setNumbers(warehousentryEntity.getNumbers());
                    bean.setCreatedBy(LoginUtil.getUsername());
                    bean.setWarehousingTime(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                    bean.setCreatedTime(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                    list.add(bean);

                    StoreChange storeChange = new StoreChange();
                    storeChange.setWarehouseentrynumber(warehousentryEntity.getNumbers());
                    storeChange.setMaterialcode(jsonObj.getObj("code").toString());
                    storeChange.setMaterialsnmark(jsonObj.getObj("taxsh").toString());
                    storeChange.setNameofmaterial(jsonObj.getObj("name").toString());
//                    storeChange.setMaterialswarehouse(jsonObj.getObj("warehouseName").toString());
                    storeChange.setTypeofchange(warehousentryEntity.getType());
                    storeChange.setChangebehavior("入库修改");
                    storeChange.setQuantityofchange("0");
                    storeChange.setQuantityinstock(String.valueOf(totalStock));
                    storeChange.setAvailablestock(String.valueOf(totalStock));
                    storeChange.setLockininventory("0");
                    storeChange.setTimeofchange(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                    storeChange.setCreatedTime(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                    storeChange.setCreatedBy(LoginUtil.getUsername());
                    storeChange.setAreanameFk(warehousentryEntity.getAreaId());
                    storeChange.setStorenameFk(warehousentryEntity.getStoreId());
                    storeChangeService.save(storeChange);
                }
            }
            //批量插入数据
            materialsService.saveBatch(list);
        }
        return ApiResult.success("修改入库单数据成功！");
    }


    @PostMapping("/updateStatus")
    @Operation(summary = "审核入库单状态")
    public ApiResult updateStatus(@RequestBody WarehousentryDto warehousentryDto) throws Exception {
        Warehousentry warehousentryEntity=new Warehousentry();
        warehousentryEntity.setId(warehousentryDto.getId());
        warehousentryEntity.setExamineTime(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
        warehousentryEntity.setExamineUser(LoginUtil.getUsername());
        warehousentryEntity.setStatus(warehousentryDto.getStatus());
        warehousentryEntity.setExamineContent(warehousentryDto.getExamineContent());
        warehousentryService.updateById(warehousentryEntity);
        return ApiResult.success("审核成功！");
    }

    private static AtomicInteger counter = new AtomicInteger(0);

     public String generateOrderNumber(String storeCode) {
        LocalDateTime now = LocalDateTime.now();
        String formattedDate = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        long sequenceNumber = new Date().getTime();
        return "rk_" + storeCode + "_" + formattedDate + "_" + sequenceNumber;
    }

    @PostMapping("/import")
    public ApiResult myImport(@RequestPart MultipartFile file) {
        try {
            //获取文件名
            String filename = file.getOriginalFilename();
            System.out.println(filename);
            if (filename==null||filename==""){
                return ApiResult.error("file不存在");
            }
            //获取文件流
            InputStream inputStream = file.getInputStream();
            //实例化实现了AnalysisEventListener接口的类
            ExcelListener listener = new ExcelListener();

            EasyExcelFactory.read(inputStream, Materials.class, listener).headRowNumber(1).build().readAll();
            //获取数据
            List<Object> list = listener.getDatas();
            if (list.size() > 1) {
                //增加物料
                List<Materials> materialsList = new ArrayList<>();
                //所有供应商
                List<Supplier> supplierList = supplierService.list();
                //所有门店
                List<Store> storeList = storeService.list();
                //所有物料类型
                List<WlType> typeList = wlTypeService.list();
                //所有战区
                List<Area> areaList = areaService.list();
                //所有物料仓库
                List<Warehouse> warehouseList = warehouseService.list();

                //通过物料仓库名称获取物料仓库信息
                Warehouse warehouse = new Warehouse();
                //通过门店名称获取门店信息
                Store store = new Store();
                //通过战区名称获取战区信息
                Area area = new Area();
                //入库单号
                String numbers = "";
                //物料总数
                int numCount = 0;
                //物料总价格
                double moneyCount = 0.00;
                for (int i = 0; i < list.size(); i++) {
                    Materials materials = (Materials) list.get(i);
                    //通过供应商名称获取供应商信息
                    Supplier supplier = supplierList.stream().filter(o -> o.getName().equals(materials.getSupplierName())).findFirst().get();
                    //通过物料类型名称获取物料类型信息
                    WlType wlType = typeList.stream().filter(o -> o.getName().equals(materials.getTypeName())).findFirst().get();
                    //因为物料仓库、门店名称、战区名称都是一样的  所以只需要赋值一次就行
                    if (i==0){
                        //通过物料仓库名称获取物料仓库信息
                        warehouse = warehouseList.stream().filter(o -> o.getName().equals(materials.getWarehouseName())).findFirst().get();
                        //通过门店名称获取门店信息
                        store = storeList.stream().filter(o -> o.getName().equals(materials.getStoreName())).findFirst().get();
                        //通过战区名称获取战区信息
                        area = areaList.stream().filter(o -> o.getName().equals(materials.getAreaName())).findFirst().get();
                        //生成入库单号
                        numbers = generateOrderNumber(store.getCode());
                    }
                    materials.setNumbers(numbers);
                    materials.setStoresId(store.getId());
                    materials.setAreaId(area.getId());
                    materials.setWarehouseId(warehouse.getId());
                    materials.setSupplierId(supplier.getId());
                    materials.setTypeid(wlType.getId());
                    materials.setTypeid(wlType.getId());
                    materials.setAvailableInventory(String.valueOf(materials.getTotalStock()));
                    materials.setLockInventory("0");
                    materials.setCreatedBy(LoginUtil.getUsername());
                    materials.setWarehousingTime(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                    materials.setCreatedTime(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                    materialsList.add(materials);
                    //获取物料件数
                    int count = materials.getTotalStock();
                    //获取物料成本价
                    double money = Double.parseDouble(materials.getCostprice());
                    numCount += count;
                    moneyCount += count*money;

                }
                WarehousentryDto warehousentryDto = new WarehousentryDto();
                warehousentryDto.setCreatorTime(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                warehousentryDto.setCreatedTime(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                warehousentryDto.setCreatorUser(LoginUtil.getUsername());
                warehousentryDto.setCreatedBy(LoginUtil.getUsername());
                warehousentryDto.setStoreId(store.getId());
                warehousentryDto.setAreaId(area.getId());
                warehousentryDto.setWarehouseId(warehouse.getId());
                warehousentryDto.setType("采购入库");
                warehousentryDto.setMaterialTypeNum(list.size());
                warehousentryDto.setMaterialNum(numCount);
                warehousentryDto.setNumbers(numbers);
                warehousentryDto.setMoney(moneyCount);

                Warehousentry warehousentryEntity=new Warehousentry();
                BeanUtil.copyProperties(warehousentryDto,warehousentryEntity);
                boolean flag = warehousentryService.save(warehousentryEntity);
                //判断入库单是否添加成功  添加成功我们物料才加门店物料库
                if (flag){
                    materialsService.saveBatch(materialsList);
                    for (Materials materials:materialsList) {
                        StoreChange storeChange = new StoreChange();
                        storeChange.setWarehouseentrynumber(warehousentryEntity.getNumbers());
                        storeChange.setMaterialcode(materials.getCode());
                        storeChange.setMaterialsnmark(materials.getTaxsh());
                        storeChange.setNameofmaterial(materials.getName());
                        storeChange.setMaterialswarehouse(warehouse.getName());
                        storeChange.setTypeofchange(warehousentryEntity.getType());
                        storeChange.setChangebehavior("入库新增");
                        storeChange.setQuantityofchange("0");
                        storeChange.setQuantityinstock(String.valueOf(materials.getTotalStock()));
                        storeChange.setAvailablestock(String.valueOf(materials.getTotalStock()));
                        storeChange.setLockininventory("0");
                        storeChange.setTimeofchange(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                        storeChange.setCreatedTime(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                        storeChange.setCreatedBy(LoginUtil.getUsername());
                        storeChange.setAreanameFk(warehousentryEntity.getAreaId());
                        storeChange.setStorenameFk(warehousentryEntity.getStoreId());
                        storeChangeService.save(storeChange);
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ApiResult.success("导入成功",200);
    }

    @PostMapping("/download")
    @Operation(tags = "Post",description = "下载文件")
    public void download(@RequestBody WarehousentryQuery warehousentryQuery,HttpServletResponse response){
        //WarehousentryQuery warehousentryQuery = new WarehousentryQuery();
        if(StringUtils.isNotBlank(warehousentryQuery.getStartDate())){
            warehousentryQuery.setStartDate(warehousentryQuery.getStartDate()+" 00:00:00");
            warehousentryQuery.setEndDate(warehousentryQuery.getEndDate()+" 23:59:59");
        }
        List<WarehousentryExcel> list = warehousentryService.getDownloadList(warehousentryQuery);


        OutputStream outputStream = null;
        try {
            response.setCharacterEncoding("UTF-8");
            String excelName = URLEncoder.encode("warehousentry_"+ LocalDateTime.now(), "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + excelName + ".xlsx");
            // 以字节流的形式输出响应正文
            outputStream = response.getOutputStream();
            try (ExcelWriter excelWriter = EasyExcel.write(outputStream, WarehousentryExcel.class).build()) {
                WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
                excelWriter.write(list,writeSheet);
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }

    @PostMapping("/upload")
    public ApiResult upload(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        // 设置编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        //获取上传到文件
        Part file = request.getPart("file");
        //获取文件信息
        //获取最后一次出现.的位置
        int index = file.getSubmittedFileName().lastIndexOf(".");
        //截取文件类型
        String type =  file.getSubmittedFileName().substring(index,file.getSubmittedFileName().length());
        //截取文件名
        String name =  file.getSubmittedFileName().substring(0,index);
        String filenames = new Date().getTime()+type;
        String filename = "D:/upload/" + filenames;
        File folder = new File("D:/upload");
        if (!folder.exists()) {
            folder.mkdirs();
        }
        ServletInputStream is = request.getInputStream();
        //把文件写入到磁盘中的指定目录
        file.write(filename);
//        byte[] arr=new byte[1024];
//        int a=0;
//        FileOutputStream fos = new FileOutputStream(filename);
//        try {
//            while((a=is.read(arr))!=-1){
//                fos.write(arr,0,a);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            fos.close();
//            is.close();
//        }
        Map<String,String> map = new HashMap<>();
        map.put("url",filename);
        map.put("filename",filenames);
        map.put("name",name);
        return ApiResult.success("导入成功",map);
    }

    @GetMapping("/getImgUrl/{filename}")
    public void getImgUrl(@PathVariable(value = "filename") String filename, HttpServletResponse response) throws ServletException, IOException {
        try {
            //根据用户的图片路径，创建文件
            //File file = new File(user.getImgUrl());
            File file = new File("D:/upload/"+filename);
            FileInputStream fileInputStream = new FileInputStream(file);
            long size = file.length();
            byte[] temp = new byte[(int) size];
            fileInputStream.read(temp, 0, (int) size);
            fileInputStream.close();
            byte[] data = temp;
            response.setContentType("image/png");
            OutputStream os = response.getOutputStream();
            os.write(data);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/getSingularCount")
    @Operation(summary = "统计总单数",description = "统计总单数")
    public ApiResult getSingularCount(@RequestBody WarehousentryQuery warehousentryQuery){
        //获取总入库单数
        int one = warehousentryService.getSingularCount(warehousentryQuery);
        //获取总出库单数
        int two = outboundService.getSingularCount(warehousentryQuery);
        //获取总销售单数
        int three = SalesslipService.getSingularCount(warehousentryQuery);
        // 获取当前日期
        Date currentDate = new Date();
        // 创建SimpleDateFormat对象，指定日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 格式化日期
        String formattedDate = dateFormat.format(currentDate);
        warehousentryQuery.setStartDate(formattedDate+" 00:00:00");
        warehousentryQuery.setEndDate(formattedDate+" 23:59:59");
        //获取今日入库单数
        int four = warehousentryService.getSingularCount(warehousentryQuery);
        //获取今日出库单数
        int five = outboundService.getSingularCount(warehousentryQuery);
        //获取今日销售单数
        int six = SalesslipService.getSingularCount(warehousentryQuery);

        Map<String,Integer> map = new HashMap<>();
        map.put("one",one);
        map.put("two",two);
        map.put("three",three);
        map.put("four",four);
        map.put("five",five);
        map.put("six",six);
        return ApiResult.success("统计总单数成功!",map);
    }

    @PostMapping("/getWeekCount")
    @Operation(summary = "统计一周总单数",description = "统计一周总单数")
    public ApiResult getWeekCount(@RequestBody WarehousentryQuery warehousentryQuery){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        //现在日期
        String end = format.format(new Date());
        //过去七天
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, - 6);
        Date d = calendar.getTime();
        String start = format.format(d);
        JTime jt = new JTime();

        warehousentryQuery.setStartDate(start+" 00:00:00");
        warehousentryQuery.setEndDate(end+" 23:59:59");
        //获取近一周入库单数
        List<StatisticsDto> rk = warehousentryService.getWeekCount(warehousentryQuery);
        //获取近一周出库单数
        List<StatisticsDto> ck = outboundService.getWeekCount(warehousentryQuery);
        //获取近一周销售单数
        List<StatisticsDto> xs = SalesslipService.getWeekCount(warehousentryQuery);

        List<Integer> rkList = new ArrayList<>();
        List<Integer> ckList = new ArrayList<>();
        List<Integer> xsList = new ArrayList<>();
        List<String> list = jt.days(start, end);

        for (int i = 0; i < list.size(); i++) {
            Integer rkNum = 0;
            Integer ckNum = 0;
            Integer xsNum = 0;
            for (int j = 0; j < rk.size(); j++) {
                if (list.get(i).equals(rk.get(j).getMonthDay())){
                    rkNum = 1;
                    rkList.add(rk.get(j).getNum());
                    break;
                }
            }
            for (int j = 0; j < ck.size(); j++) {
                if (list.get(i).equals(ck.get(j).getMonthDay())){
                    ckNum = 1;
                    ckList.add(ck.get(j).getNum());
                    break;
                }
            }
            for (int j = 0; j < xs.size(); j++) {
                if (list.get(i).equals(xs.get(j).getMonthDay())){
                    xsNum = 1;
                    xsList.add(xs.get(j).getNum());
                    break;
                }
            }
            if (rkNum==0) {
                rkList.add(0);
            }
            if (ckNum==0) {
                ckList.add(0);
            }
            if (xsNum==0) {
                xsList.add(0);
            }
        }



        Map<String,Object> map = new HashMap<>();
        map.put("rkList",rkList);
        map.put("ckList",ckList);
        map.put("xsList",xsList);
        map.put("list",list);
        return ApiResult.success("统计一周总单数成功!",map);
    }

    @PostMapping("/getMoneyCount")
    @Operation(summary = "统计当前月门店销售总额",description = "统计当前月门店销售总额")
    public ApiResult getMoneyCount(@RequestBody WarehousentryQuery warehousentryQuery){
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 获取当前月份的第一天
        LocalDate firstDayOfMonth = currentDate.withDayOfMonth(1);
        // 获取当前月份的最后一天
        YearMonth currentYearMonth = YearMonth.from(currentDate);
        LocalDate lastDayOfMonth = currentYearMonth.atEndOfMonth();
        warehousentryQuery.setStartDate(firstDayOfMonth+" 00:00:00");
        warehousentryQuery.setEndDate(lastDayOfMonth+" 23:59:59");
        //统计当前月门店销售总额
        List<SalesChartDto> list = SalesslipService.getMoneyCount(warehousentryQuery);
        List<String> moneyList  = list.stream().map(obj -> obj.getMoney()).collect(Collectors.toList());
        List<String> nameList = list.stream().map(obj -> obj.getName()).collect(Collectors.toList());
        Map<String,Object> map = new HashMap<>();
        map.put("moneyList",moneyList);
        map.put("nameList",nameList);
        return ApiResult.success("统计当前月门店销售总额成功!",map);
    }

}

